package com.wish233.wiliwilirelations.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish233.wiliwiliapi.client.UserClient;
import com.wish233.wiliwiliapi.domain.dto.UserDTO;
import com.wish233.wiliwilirelations.domain.dto.FollowRequest;
import com.wish233.wiliwilirelations.domain.po.Follow;
import com.wish233.wiliwilirelations.mapper.FollowMapper;
import com.wish233.wiliwilirelations.service.FollowService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.wish233.wiliwilirelations.domain.constant.RedisConstant.FOLLOW_KEY;

/**
 * @author WHH
 * @description 针对表【follow】的数据库操作Service实现
 * @createDate 2025-06-04 21:20:44
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow>
        implements FollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private UserClient userClient;

    @Override
    public Boolean follow(FollowRequest followRequest) {
        //查询是否关注，通过Redis的zset
        String userID = (String) StpUtil.getLoginId();
        String key = FOLLOW_KEY + userID;
        Integer followerId = followRequest.getFollowerId();
        Double score = stringRedisTemplate.opsForZSet().score(key, followerId);
        if (score == null) {
            stringRedisTemplate.opsForZSet().add(key, String.valueOf(followerId), System.nanoTime());
            // TODO 异步发送MQ消息存储到数据库
            return true;
        } else {
            //如果已经关注，执行取消关注
            stringRedisTemplate.opsForZSet().remove(key, String.valueOf(followerId));
            // TODO 异步发送MQ消息存储到数据库
            return false;
        }
    }

    @Override
    public List<UserDTO> listNowUserFollowers() {
        String userID = (String) StpUtil.getLoginId();
        String key = FOLLOW_KEY + userID;
        // 从Redis查出所有的关注的key并按score(时间戳)降序排序
        Set<String> followerIds = stringRedisTemplate.opsForZSet().reverseRange(key, 0, -1);
        if (followerIds == null || followerIds.isEmpty()) {
            return Collections.emptyList();
        }
        // 使用feign远程获取所对应的userDTO
        return userClient.getUserByIdBatchSorted(followerIds
                .stream()
                .map(Long::parseLong)
                .collect(Collectors.toSet()));
    }

    @Override
    public List<UserDTO> getFans() {
        String userID = (String) StpUtil.getLoginId();
        //从数据库查询这个用户所有的粉丝
        Set<Long> fans = list(new QueryWrapper<Follow>().eq("follower_id", userID).eq("is_delete", 0))
                .stream().map(Follow::getFollowerId).collect(Collectors.toSet());
        return userClient.getUserByIdBatchSorted(fans);
    }
}




